const express = require("express");
const router = express.Router();

function getRandomId() {
  return Math.floor(Math.random() * 1000000);
}

function dataChange(pageNumber = 1, pageSize = 10, data) {
  const startIndex = (Number(pageNumber) - 1) * Number(pageSize);
  const endIndex = startIndex + Number(pageSize);
  const currentData = data.slice(startIndex, endIndex);
  const result = {
    code: 0,
    data: {
      record: currentData,
      pageNumber: +pageNumber,
      pageSize: +pageSize,
      totalItems: data.length,
      totalPages: Math.ceil(data.length / pageSize),
    },
  };
  return result;
}

const loanData = Array.from({ length: 20 }, (_, index) => ({
  borrower: `借款人${index + 1}`,
  amount: Math.floor(Math.random() * 50000) + 10000,
  id: getRandomId(),
}));

// 查询所有贷款信息
router.get("/loans", (req, res) => {
  let resultData = loanData;
  const filters = req.query;
  if (Object.keys(filters).length > 0) {
    resultData = loanData.filter((product) =>
      Object.keys(filters).every((key) => {
        // 没有直接返回true
        if (!product[key]) {
          return true;
        }
        return String(product[key])
          .toLowerCase()
          .includes(String(filters[key]).toLowerCase());
      })
    );
  }
  const data = dataChange(req.query.pageNumber, req.query.pageSize, resultData);
  res.setHeader("Content-Type", "application/json");
  res.send(JSON.stringify(data));
});

// 查询单个贷款信息
router.get("/loans/:id", (req, res) => {
  const loanId = parseInt(req.params.id);
  const loan = loanData.find((l) => l.id === loanId);
  if (loan) {
    res.json(loan);
  } else {
    res.status(404).json({ error: "贷款信息未找到" });
  }
});

// 添加贷款信息
router.post("/loans", (req, res) => {
  const newLoan = req.body;
  if (!newLoan || !newLoan.borrower || !newLoan.amount) {
    res.status(400).json({ error: "数据不完整" });
  } else {
    newLoan.id = getRandomId();
    loanData.unshift(newLoan);
    res.json({ message: "贷款信息添加成功", data: newLoan });
  }
});

// 修改贷款信息
router.put("/loans/:id", (req, res) => {
  const loanId = parseInt(req.params.id);
  const updatedLoan = req.body;
  const index = loanData.findIndex((l) => l.id === loanId);
  if (index !== -1) {
    loanData[index] = { ...loanData[index], ...updatedLoan };
    res.json({ message: "贷款信息修改成功", data: loanData[index] });
  } else {
    res.status(404).json({ error: "贷款信息未找到" });
  }
});

// 删除贷款信息
router.delete("/loans/:id", (req, res) => {
  const loanId = parseInt(req.params.id);
  const index = loanData.findIndex((l) => l.id === loanId);
  if (index !== -1) {
    const deletedLoan = loanData.splice(index, 1);
    res.json({ message: "贷款信息删除成功", data: deletedLoan });
  } else {
    res.status(404).json({ error: "贷款信息未找到" });
  }
});

module.exports = router;
